package com.easylinkin.sm.context;


import com.easylinkin.sm.context.SmLoginInfo;
import com.easylinkin.sm.entity.Customer;
import com.easylinkin.sm.entity.Department;
import com.easylinkin.sm.entity.Menu;
import com.easylinkin.sm.entity.Privilege;
import com.easylinkin.sm.entity.Role;
import com.easylinkin.sm.entity.User;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import site.morn.bean.annotation.Target;
import site.morn.framework.context.AccountContext;
import site.morn.framework.context.LoginInfoProducer;
import site.morn.framework.context.dto.BaseLoginInfo;

/**
 * 登录信息生产者
 *
 * @author TianGanLin
 * @since 0.1.1, 2019/5/20
 */
@Target(BaseLoginInfo.class)
public class SmLoginInfoProducer implements LoginInfoProducer<BaseLoginInfo> {

  @Override
  public BaseLoginInfo product() {
    User user = AccountContext.currentUser(); // 当前用户
    SmLoginInfo loginInfo = new SmLoginInfo();
    if (Objects.isNull(user)) {
      this.emptyLoginInfo(loginInfo);
    } else {
      this.generateLoginInfo(loginInfo);
    }
    return loginInfo;
  }

  /**
   * 构建新的登录信息
   */
  protected void generateLoginInfo(SmLoginInfo loginInfo) {
    Customer customer = AccountContext.active(Customer.class); // 当前客户
    Department department = AccountContext.activeDepartment(); // 当前机构
    List<Role> roles = new ArrayList<>(AccountContext.currentRoles()); // 当前角色
    List<Privilege> privileges = new ArrayList<>(AccountContext.currents(Privilege.class)); // 系统权限
    List<Menu> menus = new ArrayList<>(AccountContext.currents(Menu.class)); // 菜单权限
    loginInfo.setUser(AccountContext.currentUser());
    loginInfo.setCustomer(customer);
    loginInfo.setDepartment(department);
    loginInfo.setRoles(roles);
    loginInfo.setPrivileges(privileges);
    loginInfo.setMenus(menus);
  }

  /**
   * 构建空的登录信息
   */
  protected void emptyLoginInfo(SmLoginInfo loginInfo) {
    loginInfo.setRoles(Collections.emptyList());
    loginInfo.setPrivileges(Collections.emptyList());
    loginInfo.setMenus(Collections.emptyList());
  }
}
